<?php 
class baseDAO extends CI_Model {

	var $tabla		= "";
	var $llave		= "";
	var $sql		= "";
	VAR $requireLogin       = 0;
	
	
    function __construct()
    {
        // Call the Model constructor
        parent::__construct();
	
	$this->db->simple_query('SET lc_time_names = \'es_MX\'');
	$this->db->simple_query('SET GLOBAL log_bin_trust_function_creators  = 1');
	$this->db->simple_query('SET GLOBAL time_zone = \'America/Cancun\'');	

    }



    function getNextItem($id,$sql=array())
    {
	
	if(count($sql) > 0)
		$this->db->where($sql);
	
	$this->db->where($this->llave." >" , $id);
	$this->db->order_by($this->llave,"ASC");
	$this->db->limit(1);
	
	$query = $this->db->get($this->tabla);
	$record =  $query->row();
	
	if(count($record) > 0)
		return $record;
	else
		return $this->getFirstItem($sql);
    }




    function getPrevItem($id,$sql=array())
    {
	
	if(count($sql) > 0)
		$this->db->where($sql);
		
	$this->db->where($this->llave." <" , $id);
	$this->db->order_by($this->llave,"DESC"); 
	$this->db->limit(1);
	
	$query = $this->db->get($this->tabla);
	$record =  $query->row();
	
	if(count($record) > 0)
		return $record;
	else
		return $this->getLastItem($sql);
    }




    function getLastItem($sql=array())
    {
	$this->db->order_by($this->llave,"DESC");
	
	if(count($sql) > 0)
		$this->db->where($sql);
		
	$this->db->limit(1);
	
	$query = $this->db->get($this->tabla);
	return $query->row(); 
    }




    function getFirstItem($sql=array())
    {
	
	$this->db->order_by($this->llave,"ASC");
	
	if(count($sql) > 0)
		$this->db->where($sql);
		
	$this->db->limit(1);
	
	$query = $this->db->get($this->tabla);
	return $query->row(); 
    }



    function getLastId()
    {

	$this->db->select_max($this->llave);
	$this->db->limit(1);
	
	$query = $this->db->get($this->tabla);
	$row = $query->row(); 
	
	return $row->{$this->llave};

    }




    function getMasVistos($sql=array())
    {
	
	$this->db->order_by("mobile","DESC");
	$this->_sql($sql);
	
	$this->db->where('fecha_creacion > "'.date( 'Y-m-d ',strtotime("-2 day")).'"');	
	
	$query = $this->db->get($this->tabla);
	$result =  $query->result();
	
	return $result;
    }   
   




   function getLastItems($sql=array(),$limit = 3)
   {
	$this->db->order_by("imagen","DESC");
	$this->db->order_by("fecha_creacion","DESC");
	
	
	if(count($sql) > 0)
		$this->db->where($sql);
		
		
	$this->db->limit($limit);
	
	$query = $this->db->get($this->tabla);
	$result =  $query->result();
	
	if(count($result) == 0)
		$this->getRandomItems($sql,$limit);
	
	return $result;

   }
   
   
   
   function getRandomItems($sql = array(), $limit = 3)
   {
	$this->db->order_by("imagen","DESC");
	$this->db->order_by($this->llave,"RANDOM");
	
	if(count($sql) > 0)
		$this->db->where($sql);
		
	$this->db->limit($limit);	
	$query = $this->db->get($this->tabla);
	
	return $query->result();
   }
   
   


    function getCategorias(){
    	
    	$this->load->model('categoriadao');
	
    	$data=array(
		"where" => array(
				 "tabla_propietario" => $this->tabla,
				 "total >" => "0"
				 )
    		
    	);

    	return $this->categoriadao->_select($data);
    	
    	
    }
    
    
    
    
   function findByTags($data=array())
   {
	$this->load->model('sphinxdao');
	
	
	if(isset($data["mode"]))
		$this->sphinxdao->SetMatchMode($data["mode"]);
	
	if(isset($data["order"]))
	      $this->sphinxdao->SetSortMode(SPH_SORT_EXTENDED,"@relevance DESC, ".$data["order"][0]." ".$data["order"][1]."");
       
	if(!isset($data["tabla"]))
           $data["tabla"] = $this->tabla;

	if(isset($data["select"]))
		$this->sphinxdao->SetSelect($data["select"]);
	      
	$this->sphinxdao->setTables(array($this->tabla));
	      
	      
	$page = $this->input->get("page");
	
	if(!empty($page))
		$data["page"] = $page;
	      
	if(isset($data["page"]))
 	{
			
		$page=intval($page);	
		
		$start = (PAGINACION* (intval($page)-1));
		$end   = PAGINACION;
	
		$limit[1] = $end;
		$limit[0] = $start;
		
		$this->sphinxdao->SetLimits($limit[0],$limit[1]);	
	} 


	if(isset($data["limit"]))
 	{
		$this->sphinxdao->SetLimits($data["limit"][0],$data["limit"][1]);
	}	
	      
	if(isset($data["filter"])){
		
		if(!isset($data["filter"][2]))
			$data["filter"][2] = TRUE;
		
		
		$this->sphinxdao->SetFilter($data["filter"][0],array($data["filter"][1]),$data["filter"][2]);
	}
	
	
	if(isset($data["filter2"])){
		
		if(!isset($data["filter2"][2]))
			$data["filter2"][2] = TRUE;
		
		
		$this->sphinxdao->SetFilter($data["filter2"][0],array($data["filter2"][1]),$data["filter2"][2]);
	}

		
	      
	return  $this->sphinxdao->select($data["search"]);      
   }
 
 
 

    
    
    function query($sql)
    {
    	$query = $this->db->query($sql);
    	return $query->result();
    }
    
    
    
    
    function setTabla($tabla)
    {
    	$this->tabla=$tabla;
    }
    
    
    
    function setLlave($llave)
    {
    	$this->llave=$llave;
    }
    
  
    
    function _insert($data=array())
    {
	
	$this->load->model('usuariodao'); 
	
    	if(count($data) >0 && is_array($data))
    	{
    		
    		if ($this->db->field_exists('usuario_creador_k', $this->tabla))
    		{
    			$log=array(
				"usuario_creador_k" => $this->usuariodao->getId()
    				);
    				
    			$data=array_merge($data,$log);	
    		}
  
    		if ($this->db->field_exists('fecha_creacion', $this->tabla))
    		{
    			$log=array(
    				"fecha_creacion"    => date('Y-m-d H:i:s')
    				);
    				
    			$data=array_merge($data,$log);	
    		}  
    	    
    		
       	 	$this->db->insert($this->tabla, $data); 
       	 	return $this->db->insert_id();
    	}else
        	return 0;
    }
    
    
    
    
    function insert($data=array()){
    	
    	return $this->_insert($data);
    	
    }
    
    
    
    
    function _delete($id){
    	
    	if(!empty($id))
    	{
    		if ($this->db->field_exists('activo', $this->tabla))
    			return $this->db->update($this->tabla, array("activo"=>0), array($this->llave => $id));
    		else
    			return $this->db->delete($this->tabla, array($this->llave => $id)); 		
    	}else
    		return 0;
    	
    }
    
    
    
    
    function delete($id){
    	
    	return $this->_delete($id);
    	
    }
    
    
    
    
    
    function _set($data=array(),$id_or_where=array())
    {
	

	$id = $this->_getId($id_or_where);

	
	if($id==0 || empty($id))
		$id = $this->_insert($data);
	else
		$this->_update($data,$id_or_where);
	
    		
    	return $id;	
    	
    }
    
    
    
    
    
    function set($data=array(),$id_or_where=array())
    {
    	return $this->_set($data,$id_or_where);
    }
    
    
    

    
    function _update($data=array(),$id_or_where){

	$this->load->model('usuariodao'); 

    	if(count($data) >0 && is_array($data))
    	{
    	
        	if ($this->db->field_exists('fecha_modificacion', $this->tabla))
    		{
    			$log=array(
    				"fecha_modificacion"	=> date('Y-m-d H:i:s')
    				);
    				
    			$data=array_merge($data,$log);		
    		}
		
		
        	if ($this->db->field_exists('usuario_modificador_k', $this->tabla))
    		{
    			$log=array(
				"usuario_modificador_k" => $this->usuariodao->getId()
    				);
    				
    			$data=array_merge($data,$log);		
    		}
    	
	    	
    	
    	if(count($id_or_where)>0 && is_array($id_or_where))
    		return $this->db->update($this->tabla, $data, $id_or_where);
    	elseif(is_int($id_or_where) || is_string($id_or_where))
    		return $this->db->update($this->tabla, $data, array($this->llave => $id_or_where));
    	else
    		return 0;	
    	
    	}else
    		return 0;	
    	
    }
    
    
    
    
    
    
    function update($data=array(),$id_or_where){
    	
    	return $this->_update($data,$id_or_where);
    	
    }
    
    
    
    
    
    function _findById($id){
	
	$result = array();
	
	if(is_array($id))
	{
		$this->db->where_in($this->llave,$id);
		$query = $this->db->get($this->tabla); 
		$result = $query->result();
	}
	else
	{
		$this->db->where(array($this->llave => $id));
		$query = $this->db->get($this->tabla); 
		$result = $query->row();
	}      
        
    	
    	if(!empty($id))
    		return $result;
    	else
        	return 0;	
    	
    }
    
    
    
    
    function findById($id)
    {
	return $this->_findById($id);
    }
    
    
    
    
    function _count($where=array()){
    	

	    $this->_select($where);
    	    return $this->db->count_all_results($this->tabla);
    		
    }
    
    function count($where=array()){
    	
    	return $this->_count($where);
    	
    }
    
    
    
    
    function setVisita($id)
    {
        $this->_setVisita($id);
    }
    
    
    
    
    
    function _setVisita($id)
    {
	
	$this->db->set('visitas', 'visitas+1', FALSE);
	$this->db->set('fecha_modificacion', 'NOW()', FALSE);
	
	$this->db->where('tabla_propietario', $this->tabla);
	$this->db->where('llave_propietario', $id);
	$this->db->update('documentos_resumen');		
	
        
    }
    
    
    
    
    
    function _sql($data=array()){
	
	$this->load->model('usuariodao');

	$select = "*";
	$random =FALSE;
	$from  = "";
    	$where = "";
    	$order = "";
    	$limit = "";
	$page = $this->input->get("page");


	if(isset($data["group_by"]))
		$this->db->group_by($data["group_by"]);
		
    	if(isset($data["random"]))
		$random = $data["random"];
    	
    	if(isset($data["select"]))
		$select = $data["select"];	
	
    	if(isset($data["where"]))
		$where = $data["where"];

	if(isset($data["order"]))
		$order = $data["order"];
 
    	if(isset($data["page"]))
		$page = $data["page"]; 
 
 
 
	if(isset($data["select"]))
		$this->db->select($data["select"],FALSE);
 	
	if(!empty($page))
 	{
			
		$page=intval($page);	
		
		$start = (PAGINACION* (intval($page)-1));
		$end   = PAGINACION;
	
		$data["limit"] = array($start,$end);
		
	}
	

	
	
	if(isset($data["from"]))
	{

		if ($this->db->field_exists('usuario_creador_k', $data["from"]) && $this->requireLogin)
		{
			if($this->usuariodao->getRolK()!=1){ // super admon
				
				$us = array("usuario_creador_k" => $this->usuariodao->getId());
				
				//$where = array_merge($us,$where);
				
				$this->db->where($us);
			}
		}	
		
		
		if ($this->db->field_exists('activo', $data["from"]))
		{
			//if (!array_key_exists('activo', $where)){
				//$where=array_merge($where,array("activo"=>1));
				
				$this->db->where(array("activo"=>1));
			//}
				
		}
		
	}


	if(isset($data["random"]))
		$this->db->order_by($this->llave,"RANDOM");
		
		
	
	if(!isset($data["order"]) and !isset($data["where"]))
		$where = $data;
	

    	if(isset($data["where"]))
    		$this->db->where($data["where"]);

    	if(isset($data["where_in"]))
    		$this->db->where_in($data["where_in"][0],$data["where_in"][1]);

    	if(isset($data["group_by"]))
    		$this->db->group_by($data["group_by"]); 
    	
	if(isset($data["order"]))
		$this->db->order_by($order[0],$order[1]); 

	if(isset($data["limit"]))
		$this->db->limit(intval($data["limit"][1]),intval($data["limit"][0]));
		
	if(isset($data["from"]))
		$this->db->from($this->tabla);
    		
    }
    
    
    
    
    function _select($data=array()){

    	$result =array();

	
	$data = array_merge($data,array("from"=>$this->tabla));

	$this->_sql($data);	
	$query = $this->db->get();

	$result = $query->result();
	//$count = count($result);
	
	/*
	if($count == 1)
	  $result = $result[0];
	*/ 

    	
    	return $result; 	
    	
    }
    
    
    
    
    
    
    function select($data=array()){
    	
    	return $this->_select($data);
    	
    }
    
    

    
    function _getId($data=array())
    {
    	$id=0;
    	

    	if(count($data)>0 && is_array($data) ){


		if(!isset($data["where"]))
			$data = array("where"=>$data);
			
    		$row = $this->_select($data);
		
		if(count($row)>0)
			$row = $row[0];
		
		if(!empty($this->llave) and $row)
	    		$id=$row->{$this->llave};

    	}
    	
    	return $id;	
    }
    
    
    
    function getId($data=array())
    {
    	return $this->_getId($data);
    }
 

    
}

?>